﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Mang24k99.Model.Dissertation;
using Mang24k99.Business.Dissertation;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Castle.ActiveRecord;


namespace Mang24k99.Web.Dissertation.Reference
{
    public partial class Edit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                ViewState["ReferenceEditID"] = Request["ID"].ToString();
                ViewState["ReferenceEditWebID"] = Request["WEBID"].ToString();
                ViewState["PageIndex"] = Request["PageIndex"].ToString();
                selectWeb.SelectedIndex = int.Parse(ViewState["ReferenceEditWebID"].ToString()) - 1;
                selectWeb.Enabled = false;
                selectSpecialName.Enabled = false;
                if (ViewState["ReferenceEditID"].ToString() != "")
                    BindDissertationReference(ViewState["ReferenceEditID"].ToString());
            }//DisID
            catch { ViewState["ReferenceEditID"] = ""; ViewState["ReferenceEditWebID"] = ""; ViewState["DisFileLength"] = ""; }

            if (!IsPostBack)
                BindDissertion();
        }

        private static string UpFilePath = ConfigurationManager.AppSettings["UploadFilePath"].ToString();

        protected void selectWeb_SelectedIndexChanged(object sender, EventArgs e)
        {
            SpecialWeb.Text = selectWeb.SelectedItem.Text;
            BindDissertion();
        }

        /// <summary>
        /// 绑定专题
        /// </summary>
        private void BindDissertion()
        {
            string webID = selectWeb.SelectedValue;
            IList<Dissert> dissert = new List<Dissert>();
            dissert = BDissertations.FindDissertations(int.Parse(webID), false);
            if (!string.IsNullOrEmpty(ViewState["ReferenceEditID"].ToString()))
            {
                foreach (Dissert aDis in dissert)
                {
                    if (aDis.ID == ViewState["ReferenceEditID"].ToString())
                    {
                        selectSpecialName.Items.Add(new ListItem(aDis.Name, aDis.ID));
                        OK.Text = "修改";
                        ViewState["DISID"] = aDis.ID;
                        break;
                    }
                }
            }
            else
            {
                selectSpecialName.DataSource = dissert;
                selectSpecialName.DataTextField = "Name";
                selectSpecialName.DataValueField = "ID";
                selectSpecialName.DataBind();
            }
        }

        /// <summary>
        /// 绑定专题的附件
        /// </summary>
        /// <param name="disID"></param>
        private void BindDissertationReference(string disID)
        {
            using (new SessionScope())
            {
                MDissertations aMdis = MDissertations.Find(int.Parse(disID));
                IList<MDissertationToFile> mdisFile = aMdis.DissertationToFile;//MDissertationToFile.Find("DissertationID", int.Parse(disID));
                ViewState["DisFileLength"] = mdisFile.Count;                      //已经添加的附件的个数
                int index = 1;
                if (mdisFile != null && mdisFile.Count > 0)
                {
                    foreach (MDissertationToFile aMdisFile in mdisFile)
                    {
                        TextBox tb = new TextBox();
                        tb.ID = "tb" + index.ToString();
                        tb.Style.Add("width", "400px");
                        tb.MaxLength = 30;

                        HiddenField hf = new HiddenField();
                        hf.ID = "tbID" + index.ToString();
                        if (!IsPostBack)
                        {
                            tb.Text = aMdisFile.FileTitle;
                            hf.Value = aMdisFile.RecordID + "+" + aMdisFile.FilePath;
                        }
                        editDisFile.Controls.Add(new LiteralControl("<tr><td class=\"tb_txt1\">相关参考文件" + index.ToString() + ":</td><td class=\"tb_txt1\">"));
                        editDisFile.Controls.Add(tb);
                        editDisFile.Controls.Add(hf);
                        editDisFile.Controls.Add(new LiteralControl("</td></tr>"));

                        FileUpload fu = new FileUpload();
                        fu.ID = "fu" + index.ToString();
                        fu.Style.Add("width", "400px");
                        editDisFile.Controls.Add(new LiteralControl("<tr><td class=\"tb_txt1\">附件" + index.ToString() + ":</td><td class=\"tb_txt1\">"));
                        editDisFile.Controls.Add(fu);

                        editDisFile.Controls.Add(new LiteralControl("</td></tr>"));
                        index++;
                    }
                }
                else
                    OK.Enabled = false;
            }
        }

        protected void OK_Click(object sender, EventArgs e)
        {
            MDissertations aDiss = new MDissertations();
            aDiss = MDissertations.Find(int.Parse(selectSpecialName.SelectedValue));
            int webID = int.Parse(selectWeb.SelectedValue);
            string filePath = string.Empty;
            string extension = string.Empty;
            bool isSuccess = false;
            string messageInfo = string.Empty;

            if (!string.IsNullOrEmpty(ViewState["DisFileLength"].ToString()) && int.Parse(ViewState["DisFileLength"].ToString()) > 0)//修改
            {
                for (int x = 1; x <= int.Parse(ViewState["DisFileLength"].ToString()); x++)
                {
                    TextBox tb = editDisFile.FindControl("tb" + x.ToString()) as TextBox;
                    HiddenField hf = editDisFile.FindControl("tbID" + x.ToString()) as HiddenField;
                    FileUpload fu = editDisFile.FindControl("fu" + x.ToString()) as FileUpload;
                    MDissertationToFile updateMdisFile = MDissertationToFile.Find(long.Parse(hf.Value.Split('+')[0].ToString()));
                    updateMdisFile.FileTitle = tb.Text;
                    updateMdisFile.Dissertation = aDiss;
                    if (fu.HasFile)      //如果需要更新附件
                    {
                        extension = System.IO.Path.GetExtension(fu.FileName).ToLower();
                        if (extension == ".pdf" || extension == ".doc" || extension == ".txt")
                        {
                            filePath = SavePath(fu.FileName);
                            fu.SaveAs(Request.PhysicalApplicationPath + filePath);
                            updateMdisFile.FilePath = filePath;
                            DeleteFile(hf.Value.Split('+')[1]);
                            tb.Text = "";
                            fu.Enabled = false;
                        }
                        else
                        {
                            Common.MessageBox.Show(this, "参考文件" + x.ToString() + "格式不正确!\r\n");
                            return;
                        }
                    }
                    updateMdisFile.Update();
                }
                Common.MessageBox.ShowAndRedirect(this, "参考文件修改成功!", "List.aspx?WEBID=" + ViewState["ReferenceEditWebID"].ToString() + "&PageIndex=" + ViewState["PageIndex"].ToString());
                //Common.MessageBox.Show(this, "请上传新参考文件!");
            }
            else//添加
            {
                #region
                if (!string.IsNullOrEmpty(TextBox1.Text) && FileUpload1.HasFile)
                {
                    if (!BDissertationToFile.HavaEnoughReference(aDiss.DissertationID.ToString(), 20))
                    {
                        extension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
                        if (extension == ".pdf" || extension == ".doc" || extension == ".txt")
                        {
                            filePath = SavePath(FileUpload1.FileName);
                            FileUpload1.SaveAs(Request.PhysicalApplicationPath + filePath);
                            MDissertationToFile mDisFile = new MDissertationToFile();
                            mDisFile.Dissertation = aDiss;
                            mDisFile.DissertationWeb = webID;
                            mDisFile.FileTitle = TextBox1.Text.Trim();
                            mDisFile.FilePath = filePath;
                            mDisFile.BDeleted = 1;
                            mDisFile.Create();
                            isSuccess = true;
                            TextBox1.Text = "";
                            messageInfo += "参考文件1上传成功!\r\n";
                        }
                        else
                            messageInfo += "上传文件1格式不正确!\r\n";
                    }
                    else
                        Common.MessageBox.ShowAndRedirect(this, "该专题已经上传20个参考文件!", "List.aspx");
                }
                if (!string.IsNullOrEmpty(TextBox2.Text) && FileUpload2.HasFile)
                {
                    if (!BDissertationToFile.HavaEnoughReference(aDiss.DissertationID.ToString(), 20))
                    {
                        extension = System.IO.Path.GetExtension(FileUpload2.FileName).ToLower();
                        if (extension == ".pdf" || extension == ".doc" || extension == ".txt")
                        {
                            filePath = SavePath(FileUpload2.FileName);
                            FileUpload2.SaveAs(Request.PhysicalApplicationPath + filePath);
                            MDissertationToFile mDisFile = new MDissertationToFile();
                            mDisFile.Dissertation = aDiss;
                            mDisFile.DissertationWeb = webID;
                            mDisFile.FileTitle = TextBox2.Text.Trim();
                            mDisFile.FilePath = filePath;
                            mDisFile.BDeleted = 1;
                            mDisFile.Create();
                            isSuccess = true;
                            TextBox2.Text = "";
                            messageInfo += "参考文件2上传成功!\r\n";
                        }
                        else
                            messageInfo += "上传文件2格式不正确!\r\n";
                    }
                    else
                        Common.MessageBox.ShowAndRedirect(this, "该专题已经上传20个参考文件!", "List.aspx");
                }
                if (!string.IsNullOrEmpty(TextBox3.Text) && FileUpload3.HasFile)
                {
                    if (!BDissertationToFile.HavaEnoughReference(aDiss.DissertationID.ToString(), 20))
                    {
                        extension = System.IO.Path.GetExtension(FileUpload3.FileName).ToLower();
                        if (extension == ".pdf" || extension == ".doc" || extension == ".txt")
                        {
                            filePath = SavePath(FileUpload3.FileName);
                            FileUpload3.SaveAs(Request.PhysicalApplicationPath + filePath);
                            MDissertationToFile mDisFile = new MDissertationToFile();
                            mDisFile.Dissertation = aDiss;
                            mDisFile.DissertationWeb = webID;
                            mDisFile.FileTitle = TextBox3.Text.Trim();
                            mDisFile.FilePath = filePath;
                            mDisFile.BDeleted = 1;
                            mDisFile.Create();
                            isSuccess = true;
                            TextBox3.Text = "";
                            messageInfo += "参考文件3上传成功!\r\n";
                        }
                        else
                            messageInfo += "上传文件3格式不正确!\r\n";
                    }
                    else
                        Common.MessageBox.ShowAndRedirect(this, "该专题已经上传20个参考文件!", "List.aspx");
                }
                if (!string.IsNullOrEmpty(TextBox4.Text) && FileUpload4.HasFile)
                {
                    if (!BDissertationToFile.HavaEnoughReference(aDiss.DissertationID.ToString(), 20))
                    {
                        extension = System.IO.Path.GetExtension(FileUpload4.FileName).ToLower();
                        if (extension == ".pdf" || extension == ".doc" || extension == ".txt")
                        {
                            filePath = SavePath(FileUpload4.FileName);
                            FileUpload4.SaveAs(Request.PhysicalApplicationPath + filePath);
                            MDissertationToFile mDisFile = new MDissertationToFile();
                            mDisFile.Dissertation = aDiss;
                            mDisFile.DissertationWeb = webID;
                            mDisFile.FileTitle = TextBox4.Text.Trim();
                            mDisFile.FilePath = filePath;
                            mDisFile.BDeleted = 1;
                            mDisFile.Create();
                            isSuccess = true;
                            TextBox4.Text = "";
                            messageInfo += "参考文件4上传成功!\r\n";
                        }
                        else
                            messageInfo += "上传文件4格式不正确!\r\n";
                    }
                    else
                        Common.MessageBox.ShowAndRedirect(this, "该专题已经上传20个参考文件!", "List.aspx");
                }
                if (!string.IsNullOrEmpty(TextBox5.Text) && FileUpload5.HasFile)
                {
                    if (!BDissertationToFile.HavaEnoughReference(aDiss.DissertationID.ToString(), 20))
                    {
                        extension = System.IO.Path.GetExtension(FileUpload5.FileName).ToLower();
                        if (extension == ".pdf" || extension == ".doc" || extension == ".txt")
                        {
                            filePath = SavePath(FileUpload5.FileName);
                            FileUpload5.SaveAs(Request.PhysicalApplicationPath + filePath);
                            MDissertationToFile mDisFile = new MDissertationToFile();
                            mDisFile.Dissertation = aDiss;
                            mDisFile.DissertationWeb = webID;
                            mDisFile.FileTitle = TextBox5.Text.Trim();
                            mDisFile.FilePath = filePath;
                            mDisFile.BDeleted = 1;
                            mDisFile.Create();
                            isSuccess = true;
                            TextBox5.Text = "";
                            messageInfo += "参考文件5上传成功!\r\n";
                        }
                        else
                            messageInfo += "上传文件5格式不正确!\r\n";
                    }
                    else
                        Common.MessageBox.ShowAndRedirect(this, "该专题已经上传20个参考文件!", "List.aspx");
                }
                #endregion
                if(string.IsNullOrEmpty(messageInfo))
                    Common.MessageBox.Show(this, "请输入参考文件名称和选择要添加的参考文件!");
                else
                    Common.MessageBox.Show(this, messageInfo);
            }
        }

        /// <summary>
        /// 规范上传文件名称
        /// </summary>
        /// <param name="str">文件名</param>
        /// <returns></returns>
        private string SavePath(string str)
        {
            Thread.Sleep(10);
            DateTime dtnow=DateTime.Now;
            int index = str.LastIndexOf('.');
            string path = UpFilePath + dtnow.ToString("yyMMddHHmmssfff");
            return path + str.Substring(index);
        }

        /// <summary>
        /// 删除该文件
        /// </summary>
        /// <param name="dFile"></param>
        private void DeleteFile(string dFile)
        {
            string filePath=Request.PhysicalApplicationPath+dFile;
            if (File.Exists(filePath))
                File.Delete(filePath);
        }


        protected void Cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("List.aspx?WEBID=" + selectWeb.SelectedValue+"&PageIndex=1");
        }
    }
}
